<?php
	defined('_JEXEC') or die('Restricted access');
    //
	require_once(CUTEENGINE_BASE_COMPONENTS_PATH."base_component_class.php");
    require_once(CUTEENGINE_UTILS_COMPONENTS_PATH."page_importer_engine.php");

    //
    // t_page_importer
    //
	class t_page_importer extends t_base_component
	{
        // constant declaration
        // public
        
        // M
        // argoument field name
        const main_url_argument_condition_1_value = "condition_1_value";
        const main_url_argument_condition_2_value = "condition_2_value";
        
        // method name
		//const main_url_method_analyze_source_from_db = "analyze_source_from_db";
        //const main_url_method_analyze_source_from_db_label = "analyze_source_from_db";
        // db component parameter name
        const main_query_component_source_data_query = "source_data_query";
        const main_query_component_query_where_condition_1 = "query_where_condition_1";
        const main_query_component_query_where_condition_2 = "query_where_condition_2";
		const main_query_component_update_date_time_name = "update_date_time_name";
		const main_query_component_update_type = "update_type";
		const main_query_component_update_frequency = "update_frequency";
		const main_query_component_template_for_update = "template_for_update";
		const main_query_component_link_for_update = "link_per_aggiornamento";
        
        // R
		const result_separator_charater = '@';
		const result_error_separator_charater = '|';
		
		//S
        const source_data_query_repository_name = "source_data_query_query";
		//table name field
		const source_data_query_field_siti_offerte_tipo_indirizzo_per_offerte = "siti_offerte_tipo_indirizzo_per_offerte";
		const source_data_query_field_siti_offerte_indirizzo_per_offerte = "siti_offerte_indirizzo_per_offerte";
		const source_data_query_field_siti_offerte_file_per_esecuzione = 'siti_offerte_file_per_esecuzione';
		const source_data_query_field_siti_offerte_recover_link_content_start_tag = "siti_offerte_recover_link_content_start_tag";
		const source_data_query_field_siti_offerte_recover_link_content_stop_tag = "siti_offerte_recover_link_content_stop_tag";        
		// S
        const specific_parameters_position_source_data_query = 1;
        const specific_parameters_position_query_where_condition_1 = 2;
        const specific_parameters_position_query_where_condition_2 = 3;
		const specific_parameters_position_update_date_time_name = 4;
		const specific_parameters_position_update_type = 5;
		const specific_parameters_position_update_frequency = 6;
		const specific_parameters_position_template_for_update = 7;
		const specific_parameters_position_link_for_update = 8;		 		
        const specific_parameters_position_last = 9;
		// U
		const t_update_type_always = "always"; 
		const t_update_type_diurnally = "diurnally";
		const t_update_type_monthly = "monthly";
		const t_update_type_weekly = "weekly";
		
        // property declaration
        // public
		// C
		public $connection = null;
		//d
		
        // P
        public $page_importer_engine = null; //t_page_importer_engine
		
		
        
		// protected method
		// G
        static function get_help_specific_parameter($a_index)
		{
			$local_return = 'NO HELP AVAILABLE';
			/*switch ($a_index) 
            {
                case self::specific_parameters_position_:
					$local_return = '';
				break;                
			}*/
			return $local_return;
		}
        static function get_default_specific_parameter($a_index)
		{
			$local_return = '';
			//echo "a_index: $a_index<br>";
			switch ($a_index) 
            {
                /*case self::specific_parameters_position_:
					$local_return = 'TRUE';
				break;                */
			}
			return $local_return;
		}	
        protected function get_specific_parameters_position_last()
        {
            return self::specific_parameters_position_last;
        } 		
		// I
		protected function initialize_query_parameters()
		{
		    // db array parameter									
			$this->new_query_parameter(
				t_cuteengine_component::main_query_parameter_name,
				self::main_query_component_source_data_query,
				t_cuteengine_component::main_query_field_name_specific_parameters,
				"1");
			$this->new_query_parameter(
				t_cuteengine_component::main_query_parameter_name,
				self::main_query_component_query_where_condition_1,
				t_cuteengine_component::main_query_field_name_specific_parameters,
				"2");
            $this->new_query_parameter(
				t_cuteengine_component::main_query_parameter_name,
				self::main_query_component_query_where_condition_2,
				t_cuteengine_component::main_query_field_name_specific_parameters,
				"3");
            $this->new_query_parameter(
				t_cuteengine_component::main_query_parameter_name,
				self::main_query_component_update_date_time_name,
				t_cuteengine_component::main_query_field_name_specific_parameters,
				"4");
            $this->new_query_parameter(
				t_cuteengine_component::main_query_parameter_name,
				self::main_query_component_update_type,
				t_cuteengine_component::main_query_field_name_specific_parameters,
				"5");
            $this->new_query_parameter(
				t_cuteengine_component::main_query_parameter_name,
				self::main_query_component_update_frequency,
				t_cuteengine_component::main_query_field_name_specific_parameters,
				"6");
            $this->new_query_parameter(
				t_cuteengine_component::main_query_parameter_name,
				self::main_query_component_template_for_update,
				t_cuteengine_component::main_query_field_name_specific_parameters,
				"7");
			$this->new_query_parameter(
				t_cuteengine_component::main_query_parameter_name,
				self::main_query_component_link_for_update,
				t_cuteengine_component::main_query_field_name_specific_parameters,
				"8");	
		}		
		// private
		// public
		public function __construct($a_cuteengine_component,$a_query_parameter) 
		{
            global $g_javascript_namespace;
			global $g_ambient_namespace;
			parent::__construct($a_cuteengine_component,$a_query_parameter);
            //echo "CREATA classe ".get_class($this);
			
			
            $this->page_importer_engine = new t_page_importer_engine($this);
            // url argouments
            $this->new_url_argument(self::main_url_argument_condition_1_value,
				0);
			$this->new_url_argument(self::main_url_argument_condition_2_value,
				1);
            // url array method    
			//$this->new_url_method(self::main_url_method_analyze_source_from_db,
              //  self::main_url_method_analyze_source_from_db_label);
			
			//
			//$g_javascript_namespace->header_script_generator->add_meta_tag('refresh_page',"refresh","10"); 
		}
		
		// E
		public function execute_component_action()
		{
			global $g_ambient_namespace;
			//echo "g_ambient_namespace->mysql_time_zone:". $g_ambient_namespace->mysql_time_zone. "<br>";
			$this->connection = $g_ambient_namespace->connection;
			$local_function = 'analyze_source';
            if ($local_function)
			{
				//echo "ciao";
				//print_r(ob_list_handlers());
				//while (@ob_end_flush());
				//print_r(ob_list_handlers());
				//while (@ob_end_flush());
				//echo "pippo";
				$this->$local_function();
				//ob_start('ob_gzhandler',1) ;
            }
                       
           
			
		}

		// 
		public function analyze_source()
		{
			Global $g_ambient_namespace;
            Global $g_url_parameters_namespace;
            Global $g_javascript_namespace;
            
            $local_parameter = $g_url_parameters_namespace->get_parameter_by_position(0); 
           /* if ($local_parameter->request_type === t_url_parameter::request_type_no_page)
            {
                	echo "<html>
<head>
    <meta http-equiv=\"Refresh\" content=\"60\" />
</head>
<body >";
            }    
            else    
            {
                $g_javascript_namespace->header_script_generator->add_meta_tag('refresh_page',"refresh","60"); 
            }*/
			//echo "analyze_source";
            $local_condition_1_value = $this->url_argument(self::main_url_argument_condition_1_value);
            $local_condition_2_value = $this->url_argument(self::main_url_argument_condition_2_value);
            
            //echo "local_condition_1_value: $local_condition_1_value <br>";
			//echo "local_condition_2_value: $local_condition_2_value <br>";
			$local_where = '';
			if (isset($local_condition_1_value) && ($local_condition_1_value != ''))
			{
				$local_where = " WHERE ".$this->get_main_query_parameter_value(self::main_query_component_query_where_condition_1);
			}
			if (isset($local_condition_2_value) && ($local_condition_2_value != ''))
			{
				if ($local_where != '')
				{
					$local_where .= " and " . $this->get_main_query_parameter_value(self::main_query_component_query_where_condition_2);
				}
				else
				{
					$local_where = " WHERE ".$this->get_main_query_parameter_value(self::main_query_component_query_where_condition_2);
				}
			}
			// get query to import
			$local_sql = $this->get_main_query_parameter_value(self::main_query_component_source_data_query);
			//echo $local_where;
			$local_return = $this->page_importer_prepare_data_query($this,$local_where,$local_sql);
			//print_r($local_return);
			/*
			if ($local_where != '')
			{
				$local_where = $local_where . ' and (usato_da is null) and (isnull(`aggiornamenti`.`data_prossimo_aggiornamento`) or (`aggiornamenti`.`data_prossimo_aggiornamento` <= now())) LIMIT 3';			
				
			}
			else 
				$local_where = " WHERE id_aggiornamento IN (SELECT id_aggiornamento FROM `v_aggiornamenti`)";
			echo "local_where: $local_where";
            
			// imposto in uso
			$this->uniqid = uniqid();
			$local_query_query = $this->new_query(
				'imposta in uso',"
				UPDATE `aggiornamenti` SET `usato_da` = ':uniqid:',data_prossimo_aggiornamento = NOW( ) $local_where",
				//UPDATE  `aggiornamenti` SET  `usato_da` =  ':uniqid:' ".$local_where. ' and id_aggiornamento = (SELECT id_aggiornamento FROM `v_aggiornamenti` limit 0,3)',
				$this->connection);
        //
			$local_query_query = $this->get_query(
				'imposta in uso');
			$local_query_query->set_value_parameter($this->uniqid,0);
			$local_query_query->set_value_parameter($local_condition_1_value,1);	
			$local_query_query->set_value_parameter($local_condition_2_value,2);
			$local_query_query->execute_query();
		
            $local_sql .= " where usato_da = ':uniqid:' ORDER BY `data_prossimo_aggiornamento`";*/
			$local_sql = $local_return[0];
			//echo "local_sql: ".$local_sql;
			$this->new_query(
				self::source_data_query_repository_name,
				$local_sql,$this->connection);
            
			$local_query_query = $this->get_query(
				self::source_data_query_repository_name);
			$local_query_query->set_value_parameter($this->uniqid,0);

            //
            //$local_query_query->open_connection();
            try
            {
                $local_function = "analyze_source_from_db";
				$local_query_query->execute_function_from_query_result($this,$local_function);
				//
                //$local_query_query->execute_query();
                //$local_query_query->first();
                //
                
            }    
            catch(Exception $e)
            {
                $this->log->add_log_error($e);    
            }   
            //$local_query_query->close_connection();            
            //
            if ($local_parameter->request_type === t_url_parameter::request_type_no_page)
            {
                	echo "</body>
</html>";
            }              
		}        

		public function analyze_source_from_db($a_query_parameter,$a_row_no,$a_rows_count) 
		{
			//$local_row_no = $arguments[1];
			//echo "($a_row_no/$a_rows_count) <br>";
			$local_update_date_time = $a_query_parameter->sql_values[$this->get_main_query_parameter_value(self::main_query_component_update_date_time_name)];
			$local_update_type = $a_query_parameter->sql_values[$this->get_main_query_parameter_value(self::main_query_component_update_type)];
			$local_update_frequency = $a_query_parameter->sql_values[$this->get_main_query_parameter_value(self::main_query_component_update_frequency)];
			//$local_ = $a_query_parameter->sql_values
			$local_execute_import = true;
			//
			if ($local_execute_import === true)
				$this->parse_custom_page_into_mysql_table($a_query_parameter->sql_values);
			ob_flush();
		}
        // I
        public function import_from_url_as_text($a_url,$a_start_tag_array,$a_stop_tag_array)
        {
            global $g_ambient_namespace;
            // apro il link 
            $local_result = array();
            $local_content = file_get_contents($a_url);
			foreach($a_start_tag_array as $a_index => $local_start_tag)
			{
				//echo "<br>a_index: $a_index => a_start_tag_array: $local_start_tag";
				//$local_start_tag = $a_start_tag_array[$a_index];
				$local_stop_tag = $a_stop_tag_array[$a_index];
				//echo "<br>local_start_tag: $local_start_tag - local_stop_tag: $local_stop_tag";
				$local_start_complteta = t_page_importer_engine::string_position($local_content,$local_start_tag,0);
				$local_stop_complteta = t_page_importer_engine::string_position($local_content,$local_stop_tag,$local_start_complteta);
				//echo "local_start_complteta: $local_start_complteta - local_stop_complteta:$local_stop_complteta";            
				if (($local_start_complteta == '') || ($local_stop_complteta == '') || ($local_start_complteta == -1) || ($local_stop_complteta == -1))
				{
					
				//	$g_ambient_namespace->log->add_log_error("Impossibile importare i dati per il link:
				//		URL: $a_url
					//	local_start_tag: $local_start_tag - local_stop_tag: $local_stop_tag
						//local_start_complteta: $local_start_complteta - local_stop_complteta: $local_stop_complteta",NULL,true);
					break;	
				}
				else
				{
					$local_result[] = trim(strip_tags(substr($local_content,$local_start_complteta+strlen($local_start_tag),$local_stop_complteta - $local_start_complteta),'<br>'));					 
					
				}
			}
            //echo "<br>local_result: <br>$local_result<br>";
            return $local_result;
        }    


        // P
        private function parse_custom_page_into_mysql_table($a_value)
        {
			//$local_update_file = "page_importer_extension_$this->id.php";
            global $g_ambient_namespace;
			
			try
			{
				//echo "<br>link origine dati: ".$a_value[$this->get_main_query_parameter_value(self::main_query_component_link_for_update)]. "<br>";
				//require(CUTEENGINE_PATH_CUSTOM_FILES . $local_update_file);
				$local_return = $this->page_importer_query_initialize($this,$a_value);
				//print_r($local_return);
				//
				$table_destination_name = $local_return[0];
				$local_aggiornamento_id = $local_return[1];
				$local_dettaglio_aggiornamento_id = $local_return[2];
				
				$html_name_link = $a_value[$this->get_main_query_parameter_value(t_page_importer::main_query_component_link_for_update)]	;

				//
				$local_file = $a_value[$this->get_main_query_parameter_value(self::main_query_component_template_for_update)];
				//echo "local_file(exist:". file_exists(CUTEENGINE_PATH_CUSTOM_FILES . $local_file) ."): ".CUTEENGINE_PATH_CUSTOM_FILES."$local_file<br>";
				/*echo "html_name_link:$html_name_link <br>";
                $this->log->add_a_report_log("local_file: ".CUTEENGINE_PATH_CUSTOM_FILES."$local_file");
				$this->log->add_a_report_log("html_name_link: $html_name_link");*/
            
	            
                require(CUTEENGINE_PATH_CUSTOM_FILES . $local_file);
				 
				//
			}
			catch(Exception $e)
            {
                echo "ERRORE";
				$this->log->add_log_error($e,NULL,true);    
            }
			$this->page_importer_query_finalize($this,$a_value);

        }

        
        // Parse a RSS file and save into database table having a reference parent ID in $parent_table_destination_in on a parent table
        private function parse_rss_into_mysql_table($rss_name_link,$parent_table_name,$parent_table_ID,$table_destination_name,$log,
            $recover_link_content,$start_tag_to_import,$stop_tag_to_import) 
        {
          global $g_ambient_namespace;
		  try
		  {
			// Empty $table_destination_name
            /*$sSQL = "DELETE FROM `" . $table_destination_name . "` WHERE (`" . $parent_table_name . "_id` = $parent_table_ID)";
            $oResult = mysql_query($sSQL); 
            
            If($oResult) 
			{
				$rss_log ='dati eliminati con successo';
			}
			else
			{
				// echo 'alert("ERRORE detail_where: '.mysql_errno().': '.mysql_error().' ");';  
				$local_error = "MySQL error ".mysql_errno().": ".mysql_error()." when executing:'$sSQL'";
				$rss_log = $local_error;
				$this->log->add_log_error($local_error,debug_backtrace());
			}
			if ($log)
				echo("$rss_log");
                */

            // load rss file
            $Loaded = false;
            if (PHP_VERSION>='5')
            {
                $xmlDoc = new DOMDocument();
                $Loaded = $xmlDoc->load($rss_name_link);
                $root = $xmlDoc;
                //$Loaded = true;
            }
            else
            {
                $xml = file_get_contents($rss_name_link);
                $Loaded = ($xmlDoc=domxml_open_mem($xml));
                if ($Loaded)
                {
                    $root=$xmlDoc->document_element();
                }
            }
            //
            if ($Loaded)
            {
			
                //get elements from "<channel>"
                if (PHP_VERSION>='5')
                {   
                    $channels=$root->getElementsByTagName('channel');
                    $channel = $channels->item(0);
                }	
                else
                {
                    $channels=$root->get_elements_by_tagname('channel');
                    $channel = $channels[0];
                }
                //
                //$channel_title_node_value = page_importer_engine->get_node_value($channel,'title',0);
                //
                //$channel_link_node_value = page_importer_engine->get_node_value($channel,'link',0);
                //get and output "<item>" elements
                if (PHP_VERSION>='5')
                {
                    $x=$channel->getElementsByTagName('item');
                    $item_count = $x->length;
                }	
                else
                {
                    $x=$root->get_elements_by_tagname('item');
                    $item_count = count($x);
                }			
                $local_error_count = 1;
                for ($i=0; $i <$item_count; $i++)
                {
                    $local_current_item_log = "elemento ".($i+1)." su ".$item_count."<br>";
					$pattern = '/(\s{0,}<br />){1,}/i';
					$replacement = '<br />';
                    $item_title = htmlentities($this->page_importer_engine->get_node_value($channel,'title',$i),ENT_QUOTES);
					$local_array_ln = array("\n" => '<br />', "\r\n" =>'<br />',"<br>" => '<br />',"<br/>" => '<br />');
                    $item_title = strtr($item_title, $local_array_ln);	
					$item_title = preg_replace($pattern, $replacement, $item_title);
					//
                    $item_link = $this->page_importer_engine->get_node_value($channel,'link',$i);
                    //
					$item_desc = strip_tags($this->page_importer_engine->get_node_value($channel,'description',$i)); 
                    htmlentities($item_desc,ENT_QUOTES);
                    $item_desc = strtr($item_desc, $local_array_ln);
					//echo "item_desc: " . $item_desc;
					$item_desc = preg_replace($pattern, $replacement, $item_desc);					
					//
                    $item_pubDate = $this->page_importer_engine->get_node_value($channel,'pubDate',$i);	
                    $item_guid = $this->page_importer_engine->get_node_value($channel,'guid',$i);
                    $item_guid_isPermaLink = false;
                    //
					$local_recover_link_content_error = false;
                    if (!$recover_link_content)
                    {
                        $item_OfferteCompleta = '';
						
                    }
                    else
                    {
                        // apro il link 
                        $item_OfferteCompleta = '';
                        $item_OfferteCompleta = file_get_contents($item_link);
                        
						$local_start = strpos($item_OfferteCompleta,$start_tag_to_import);
						$local_stop = strpos($item_OfferteCompleta,$stop_tag_to_import,$local_start);
							
                        if (($start_tag_to_import == '') || ($stop_tag_to_import == '') || ($local_start == -1) || ($local_stop == -1))
						{
							$local_recover_link_content_error = true;
						}
						$item_OfferteCompleta = substr($item_OfferteCompleta,$local_start,$local_stop - $local_start);					 
                        //if (get_magic_quotes_gpc() == 0)
                        //{
                        //	$item_OfferteCompleta = addslashes($item_OfferteCompleta);
                        //}
                        $item_OfferteCompleta = strip_tags($item_OfferteCompleta);
                        $item_OfferteCompleta = strtr($item_OfferteCompleta,$local_array_ln);
						$item_OfferteCompleta = preg_replace($pattern, $replacement, $item_OfferteCompleta);
                        $item_OfferteCompleta = htmlentities($item_OfferteCompleta,ENT_QUOTES);
                    }
                   // echo "$item_pubDate";
                    // save to DB
					/*"INSERT INTO `$table_destination_name` ( 
					`siti_offerte_id` , `offerte_title` , 
					`offerte_link` , 
					`offerte_description` , `offerte_pub_date`,
					`offerte_guid` , `offerte_guid_is_perma_link` ,
					`offerte_offerta_completa`)
					VALUES ("*/
                    $sSQL = "INSERT INTO `$table_destination_name` ( 
                        `".$parent_table_name."_id` , `".$table_destination_name."_title` , 
                        `".$table_destination_name."_link` , 
                        `".$table_destination_name."_description` , `".$table_destination_name."_pub_date`  ,
                        `".$table_destination_name."_guid` , `".$table_destination_name."_guid_is_perma_link` ,
                        `".$table_destination_name."_offerta_completa`)
                        VALUES (
                        '$parent_table_ID', '$item_title', '$item_link','$item_desc', '$item_pubDate', 
                        '$item_guid','$item_guid_isPermaLink','$item_OfferteCompleta');";
		
                    
                    $oResult = mysqli_query($g_ambient_namespace->connection->mysqli,$sSQL); 
                    if(($oResult) && (!$local_recover_link_content_error)) 
					{
				
						$rss_result = self::result_separator_charater.($i+1).self::result_separator_charater;
						$rss_log ='dati inseriti con successo<br>';
						echo $rss_result; 
						//echo "tab1_Comp.render ();";
					} 
                    else
                    {
                        $rss_result = self::result_error_separator_charater.$local_error_count.self::result_error_separator_charater;
						echo $rss_result;
						$local_error_count++;

						//rss_log = "ERRORE detail_where: '.mysql_errno().': '.mysql_error().' ";  
                        if (local_recover_link_content_error)
							$local_error = "Tag di importazioni inizo:'$start_tag_to_import' e fine:'$stot_tag_to_import' per l'offerta all'indirizzo:'$item_link' NON TROVATI";
						else	
							$local_error = "MySQL error ".mysqli_errno($g_ambient_namespace->connection->mysqli).": ".mysqli_error($g_ambient_namespace->connection->mysqli)." when executing:'$sSQL'";
                        $rss_log = $local_error;
						$this->log->add_log_error($local_error,debug_backtrace());
                    }
                    if ($log)
						echo("$rss_log $local_current_item_log");

                }
            }
            else
            {
                if ($log)
                {
                    $rss_log ='Impossibile caricare il il file: "'.$rss_name_link.'" a causa di: ';
					echo("$rss_log $local_current_item_log");			
				}
                
            }	
        
		  }
		  catch(Exception $e)
		  {
			$this->log->add_log_error($e);    
		  }  

		}


	}
	
	
?>